#include "messageimagelabel.h"
#include "model/datacenter.h"

MessageImageLabel::MessageImageLabel(const QString &fileId, const QByteArray &content, bool isLeft)
    :fileId(fileId),content(content),isLeft(isLeft)
{
    this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    imageBtn = new QPushButton(this);
    imageBtn->setStyleSheet("QPushButton { border: none;}");

    if(this->content.isEmpty())
    {
        //需要网络加载
        model::DataCenter* dataCenter = model::DataCenter::getInstance();
        connect(dataCenter,&model::DataCenter::getSingleFileDone,this,&MessageImageLabel::updateUI);
        dataCenter->getSingleFileAsync(fileId);

    }
}

void MessageImageLabel::updateUI(const QString &fileId, const QByteArray &content)
{
    if(this->fileId == fileId)
    {
        return;
    }

    this->content = content;
    this->update();
}

void MessageImageLabel::paintEvent(QPaintEvent *event)
{
    QObject* obj = this->parentWidget();

    if(obj == nullptr || !obj->isWidgetType())
    {
        return;
    }

    QWidget* w = dynamic_cast<QWidget*>(obj);

    int width = w->width() * 0.6;
    int height;

    QImage image;

    if(content.isEmpty())
    {
        LOG() << "MessageImageLabel::paintEvent 图片尚未加载成功";
        return;
    }

    image.loadFromData(content);

    //缩放逻辑
    if(image.width() > width)
    {
        height = (double)width * image.height() / image.width();
    }
    else
    {
        width = image.width();
        height = image.height();
    }

    QPixmap pixmap;
    pixmap.fromImage(image);

    imageBtn->setIconSize(QSize(width,height));
    imageBtn->setIcon(pixmap);

    //重设父元素高度
    w->setFixedHeight( height + 50);

    //确认按钮所在位置
    if (isLeft)
    {
        imageBtn->setGeometry(10, 0, width, height);
    }
    else
    {
        int leftPos = this->width() - width - 10;
        imageBtn->setGeometry(leftPos, 0, width, height);
    }

}






















